package KMP;

import java.util.Arrays;

public class KMPAlgorithm {
    public static void main(String[] args) {
        String str1 = "BBC ABCDAB ABCDABCDABDE";
        String str2 = "ABCDABD";
        int[] kmpnext = kmpnext(str2);
        System.out.println("部分匹配值：" + Arrays.toString(kmpnext));
        int index = kmpsearch(str1, str2, kmpnext);
        System.out.println("index:"+index);
    }

    /**
     * KMP匹配算法
     *
     * @param str1 待查找字符串
     * @param str2 需要匹配的子串
     * @param next 部分匹配值
     * @return
     */
    public static int kmpsearch(String str1, String str2, int[] next) {
        //遍历Str1
        for (int i = 0, j = 0; i < str1.length(); i++) {
            //考虑str1.charAt(i) != str2.charAt(j)
            while(j >0 && str1.charAt(i) != str2.charAt(j)){
                j=next[j-1];
            }
            //相等就j++，但是需要主要考虑不等的情况
            if (str1.charAt(i) == str2.charAt(j)) {
                j++;
            }
            if (j == str2.length()){
                return i-j+1;
            }
        }
        return -1;
    }

    public static int[] kmpnext(String dest) {
        int[] next = new int[dest.length()];//该数组就是存有部分匹配值的数组
        //第一个字母的部分匹配值为0
        next[0] = 0;
        //i 遍历dest字符数组,j负责遍历需要对比的字符
        for (int i = 1, j = 0; i < dest.length(); i++) {
            while (j > 0 && dest.charAt(i) != dest.charAt(j)) {
                j = next[j - 1];
            }
            if (dest.charAt(i) == dest.charAt(j)) {
                j++;
            }
            next[i] = j;
        }
        return next;
    }
}
